$(function () {
    let buttonGroup = [
        {
            id: 'btn_cancel_filter',
            size: 'small',
            text: '清除过滤',
            iconCls: 'icon-clear',
            plain: true,
            onClick: btn_cancel_filter
        },
        {
            id: 'btn_export',
            size: 'small',
            text: '导出Excel',
            iconCls: 'icon-page_excel',
            plain: true,
            onClick: btn_export_excel
        },
        {
            id: 'btn_print',
            size: 'small',
            text: '打印',
            iconCls: 'icon-print',
            plain: true,
            onClick: btn_print
        },
        {
            id: 'btn_grid_columns',
            size: 'small',
            text: '列',
            iconCls: 'icon-text_columns',
            plain: true,
            onClick: btn_open_column_list
        },
        {
            id: 'btn_close',
            size: 'small',
            text: '关闭',
            iconCls: 'icon-no',
            onClick: btn_close,
            plain: true
        },
    ];
    buttonGen($('#north'), buttonGroup);
    bindEnterEvents();
    let kGrid = $('#v_grid').data('kendoGrid');
    var options = kGrid.getOptions();
    if (options.columns.length > 0)
        initCombobox(options)
})

const PrintColumns = [];

//  选中事件
function onSelect(title, index) {
    switch (index) {
        case 0: // 白坯产量表 - 第一个标签页 - 白坯产量明细
            if ($('#v_grid').data('kendoGrid') == undefined) {
                grid_1();
            }
            break;
        case 1: // 白坯产量表 - 第二个标签页 - 白坯产量汇总
            if ($('#v_grid_1').data('kendoGrid') == undefined) {
                grid_2();
            }
            break;
    }
}

// 白坯产量表 - 第一个标签页 - 白坯产量明细
function grid_1() {
    let SUFFIX = "_a";
    let jth = new kendo.data.DataSource({data: []});
    let specification = new kendo.data.DataSource({data: []});
    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "jrkbill/report/greyfabric",
                dataType: "json",
                type: "GET",
                data: {
                    start: $('#start').datebox('getValue'),
                    end: $('#end').datebox('getValue'),
                    machineNum: $('#machineNum').combobox('getValue'),
                    // textField: $('#column').combobox('getValue'),
                    // valueField: $('#value').textbox('getValue'),
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    createdate: {type: "date"},
                    daynumber: {type: "number"},
                    qty: {type: "number"},
                    ps: {type: "number"},
                    averageqty: {type: "number"},
                    sumqty: {type: "number"},
                    sumps: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "ps", aggregate: "sum"},
            {field: "qty", aggregate: "sum"},
        ],
        change: function (e) {
            let data = this.data();
            specification.data(unique(data, 'specification'));
            jth.data(unique(data, 'jth'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    let columns = [
        {
            field: "no",
            title: "#",
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            template: "<span class='row_number'></span>",
            width: 40
        },
        {
            field: "jth",
            title: '机台号',
            width: 93,
            footerTemplate: '总计:',
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true, dataSource: jth}
        },
        {
            field: "createdate",
            title: '日期',
            width: 85,
            format: "{0: MM-dd}",
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
        },
        // {
        //     field: "daynumber",
        //     title: '天数',
        //     width: 85,
        //     filterable: false,
        //     headerAttributes: {style: 'text-align:center;'},
        //     attributes: {'class': 'kendo-custum-char'},
        // },
        {
            field: "specification",
            title: '规格/头份',
            width: 67,
            filterable: {multi: true, search: true, dataSource: specification},
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
        },
        {
            field: 'ps',
            title: '匹数',
            width: 80,
            template: item => {
                return item.ps ? parseFloat(item.ps).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'qty',
            title: '产量',
            width: 80,
            template: item => {
                return item.qty ? parseFloat(item.qty).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'sumps',
            title: '累计匹数',
            width: 80,
            template: item => {
                let is_last_one = item['is_last_one'] || 0;
                let sumps = item.sumps ? parseFloat(item.sumps).toFixed(0) : '';
                return is_last_one ? `<b>${sumps}</b>` : sumps;
            },
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        // {
        //     field: 'averageqty',
        //     title: '日均产量',
        //     width: 80,
        //     template: item => {
        //         let is_last_one = item['is_last_one'] || 0;
        //         let averageqty = item.averageqty ? parseFloat(item.averageqty).toFixed(1) : '';
        //         return is_last_one ? `<b>${averageqty}</b>` : averageqty;
        //     },
        //     footerAttributes: {style: 'text-align:right;'},
        //     attributes: {'class': 'kendo-custum-number'},
        //     filterable: false,
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        {
            field: 'sumqty',
            title: '累计产量',
            width: 80,
            template: item => {
                let is_last_one = item['is_last_one'] || 0;
                let sumqty = item.sumqty ? parseFloat(item.sumqty).toFixed(1) : '';
                return is_last_one ? `<b>${sumqty}</b>` : sumqty;
            },
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "isnullfield",
            title: '.',
            width: 300,
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
        },
    ];
    let grid = $("#v_grid").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "白坯产量明细表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            let kGrid = $('#v_grid').data('kendoGrid');
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field']
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
}

// 白坯产量表 - 第二个标签页 - 白坯产量汇总
function grid_2() {
    let SUFFIX = "_b";
    let jth = new kendo.data.DataSource({data: []});
    let specification = new kendo.data.DataSource({data: []});
    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "jrkbill/report/greysummary",
                dataType: "json",
                type: "GET",
                data: {
                    start: $('#start').datebox('getValue'),
                    end: $('#end').datebox('getValue'),
                    machineNum: $('#machineNum').combobox('getValue'),
                    // textField: $('#column').combobox('getValue'),
                    // valueField: $('#value').textbox('getValue'),
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    createdate: {type: "date"},
                    daynumber: {type: "number"},
                    qty: {type: "number"},
                    ps: {type: "number"},
                    averageqty: {type: "number"},
                    sumqty: {type: "number"},
                    sumps: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "ps", aggregate: "sum"},
            {field: "qty", aggregate: "sum"},
        ],
        change: function (e) {
            let data = this.data();
            specification.data(unique(data, 'specification'));
            jth.data(unique(data, 'jth'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    let columns = [
        {
            field: "no",
            title: "#",
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            template: "<span class='row_number'></span>",
            width: 40
        },
        {
            field: "jth",
            title: '机台号',
            width: 93,
            footerTemplate: '总计:',
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true, dataSource: jth}
        },

        {
            field: 'ps',
            title: '匹数',
            width: 80,
            template: item => {
                return item.ps ? parseFloat(item.ps).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'qty',
            title: '产量',
            width: 80,
            template: item => {
                return item.qty ? parseFloat(item.qty).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "daynumber",
            title: '天数',
            width: 85,
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
        },
        {
            field: 'averageqty',
            title: '日均产量',
            width: 80,
            template: item => {
                let is_last_one = item['is_last_one'] || 0;
                let averageqty = item.averageqty ? parseFloat(item.averageqty).toFixed(1) : '';
                return is_last_one ? `<b>${averageqty}</b>` : averageqty;
            },
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "isnullfield",
            title: '.',
            width: 300,
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
        },
    ];
    let grid = $("#v_grid_1").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "白坯产量汇总表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            let kGrid = $('#v_grid_1').data('kendoGrid');
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field']
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid_1').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
    grid.on('dblclick', 'tr', function (e) {
        let dataItem = $('#v_grid_1').data('kendoGrid').dataItem(e.currentTarget);
    });
    grid.on('click', 'tr', function (e) {
        let dataItem = $('#v_grid_1').data('kendoGrid').dataItem(e.currentTarget);
    })
}

function btn_cancel_filter() {
    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid').data('kendoGrid').dataSource.filter({});
            break;
        case 1:
            $('#v_grid_1').data('kendoGrid').dataSource.filter({});
            break;
    }
    $('#v_grid').data('kendoGrid').dataSource.filter({});
}

function btn_search() {
    function setCol(ele, show = []) {
        let kGrid = ele.data('kendoGrid');
        let columns = kGrid.columns;
        let checked = $('#state').switchbutton('options').checked;
        if (!checked)
            for (let col of columns) {
                if (col['field'] && show.indexOf(col['field']) == -1) {
                    kGrid.hideColumn(col);
                } else if (col['field']) {
                    kGrid.showColumn(col);
                }
            }
        else {
            for (let col of columns) {
                if (col['title'] && col['title'].indexOf('编号') > -1)
                    kGrid.hideColumn(col);
                else
                    kGrid.showColumn(col);
            }
        }
    }

    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid').data('kendoGrid').dataSource.read({
                start: $('#start').datebox('getValue'),
                end: $('#end').datebox('getValue'),
                machineNum: $('#machineNum').combobox('getValue'),
                // textField: $('#column').combobox('getValue'),
                // valueField: $('#value').textbox('getValue'),
            })
            break;
        case 1:
            $('#v_grid_1').data('kendoGrid').dataSource.read({
                start: $('#start').datebox('getValue'),
                end: $('#end').datebox('getValue'),
                // textField: $('#column').combobox('getValue'),
                // valueField: $('#value').textbox('getValue'),
            });
            break;
    }
}

function getCurrentIndex() {
    let tab = $('#tabs').tabs('getSelected');
    let index = $('#tabs').tabs('getTabIndex', tab);
    return index;
}

// 打印
function btn_print() {
    switch (getCurrentIndex()) {
        case 0:
            $.formDialog.open({
                mode: '打印选择',
                resizable: false,
                columns: PrintColumns,
                width: 435,
                height: 100,
                // width: 'auto',
                // height: 'auto',
                // top:100,
                modal: true,
                content: 'center',
                buttons: [{
                    text: '无A/B面',
                    iconCls: 'icon-print',
                    width: 130,
                    height: 90,
                    handler: e => {
                        $.get('customize/getDatabase', {}, data => {
                            if (data.success) {
                                console.log('打印请求来的数据：', data)
                                let reportlets = [{
                                    reportlet: data.data + '/白坯产量表.cpt',
                                    start: $('#start').datebox('getValue'),
                                    end: $('#end').datebox('getValue'),
                                    // machineNum: $('#machineNum').combobox('getValue'),
                                    database: data.data
                                }];
                                console.log('构建的reportlets：', reportlets)
                                window.parent.FR.doURLPDFPrint({
                                    url: $(window.parent.document.body).data('report_url'),
                                    isPopUp: false,
                                    data: {
                                        reportlets: reportlets
                                    }
                                })
                            }
                        }, 'json');
                    }
                },
                {
                    text: '有A/B面',
                    iconCls: 'icon-print',
                    width: 130,
                    height: 90,
                    handler: e => {
                        $.get('customize/getDatabase', {}, data => {
                            if (data.success) {
                                console.log('打印请求来的数据：', data)
                                let reportlets = [{
                                    reportlet: data.data + '/生产记录汇总表.cpt',
                                    start: $('#start').datebox('getValue'),
                                    end: $('#end').datebox('getValue'),
                                    class: '全部',
                                    // machineNum: $('#machineNum').combobox('getValue'),
                                    database: data.data
                                }];
                                console.log('构建的reportlets：', reportlets)
                                window.parent.FR.doURLPDFPrint({
                                    url: $(window.parent.document.body).data('report_url'),
                                    isPopUp: false,
                                    data: {
                                        reportlets: reportlets
                                    }
                                })
                            }
                        }, 'json');
                    }
                },
                {
                    text: '退出',
                    iconCls: 'icon-cancel',
                    width: 130,
                    height: 90,
                    handler: e => {
                        $.formDialog.close();
                    }
                }],
            });
                $.formDialog.disableBtn(['修改', '复制']);
            break;
        case 1:
            let reportlets = [];
            $.get('customize/getDatabase', {}, data => {
                if (data.success) {
                    reportlets.push({
                        reportlet: `${data.data}/白坯产量汇总表.cpt`,
                        start: $('#start').datebox('getValue'),
                        end: $('#end').datebox('getValue'),
                        // machineNum: $('#machineNum').combobox('getValue') || '',
                        database: data.data
                    });
                    console.log("打印参数", reportlets)
                    window.parent.FR.doURLPDFPrint({
                        url: $(window.parent.document.body).data('report_url'),
                        isPopUp: false,
                        data: {
                            reportlets: reportlets
                        }
                    })
                }
            }, 'json');
            break;
    }
}

function btn_open_column_list() {
    let kendoGridID = '';
    switch (getCurrentIndex()) {
        case 0:
            kendoGridID = '#v_grid';
            break;
        case 1:
            kendoGridID = '#v_grid_1';
            break;
    }
    let options = $(kendoGridID).data('kendoGrid').getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="resizable:true,iconCls:'icon-text_columns',width:200,height:300,modal:true,title:'列'" 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        $(kendoGridID).data('kendoGrid').showColumn(opts.name);
                    } else {
                        $(kendoGridID).data('kendoGrid').hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}

function btn_export_excel() {
    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid').data('kendoGrid').saveAsExcel();
            break;
        case 1:
            $('#v_grid_1').data('kendoGrid').saveAsExcel();
            break;
    }
}

function getCurrentSelectedGrid() {
    switch (getCurrentIndex()) {
        case 0:
            return $('#v_grid').data('kendoGrid')
        case 1:
            return $('#v_grid_1').data('kendoGrid');
    }
}

function btn_close() {
    window.parent.closeTab();
}

function stateChange(checked) {
    setState(checked);
    btn_search();
}

function setState(state) {
    if (state) {
        $('#start').datebox('enable');
        $('#end').datebox('enable');
    } else {
        $('#start').datebox('disable');
        $('#end').datebox('disable');
    }
}

//选中事件
function initCombobox(options) {
    var columns = options.columns;
    columns.splice(0, 1);
    $('#column').combobox({
        valueField: 'field',
        textField: 'title',
        data: columns,
        editable: false
    })
}